# --*-- coding:utf8 --*--
import os
import time
import pyecharts.options as opts
from pyecharts.charts import Pie, Sunburst
import xlrd

filepath = r'E:\建投-内容管理后台\cms_mapping\自动化测试数据统计.xls'
sheet = '自动化测试数据统计'
'''0-3为固定，values的值为excel中的列从0开始；
one two three version 服务接口个数 新增接口个数 用例总数 用例执行成功个数 用例执行失败个数 用例执行总数  测试总轮次  缺陷总数
'''
# values = [0, 1, 2, 3, 5, 6, 9, 10, 11, 12, 13, 20]
"""
htmlnus为对应values的数量，0-3为固定，后面有几位填几位
"""
values = {
    '自动化测试数据统计':
    # one,two,three,version,服务接口个数,新增接口个数,用例总数,用例执行成功个数,用例执行失败个数,
    # 用例执行总数,测试总轮次,缺陷总数;
        {"colflag": [0, 1, 2, 3, 5, 6, 9, 10, 11, 12, 13, 20],
         "colname": [
             "自动化服务接口个数",
             "自动化新增接口个数",
             "自动化用例总数",
             "自动化用例执行成功个数",
             "自动化用例执行失败个数",
             "自动化用例执行总数",
             "自动化测试总轮次",
             "自动化测试缺陷总数"
         ]
         }
}

htmlnus = 8
start_date = None
end_date = None


def cur_path():
    date = time.strftime("%Y-%m-%d", time.localtime()).replace(' ', ':').replace(':', ':')
    CURPATH = os.path.dirname(os.path.realpath(__file__)) + "/%s" % date
    os.makedirs(CURPATH, exist_ok=True)
    return CURPATH


CURPATH = cur_path()


def loadsheet():
    workbook = xlrd.open_workbook(filepath)
    sheet_object = workbook.sheet_by_name(sheet)
    return sheet_object


def myPie(data, name):
    """
    Pie chart style
    """
    (
        # Pie(init_opts=opts.InitOpts(width="1600px", height="800px"))
        Pie(init_opts=opts.InitOpts(width="1347px", height="540px"))
            .add(
            series_name=name,
            data_pair=data[0],
            radius=[0, "15%"],
            label_opts=opts.LabelOpts(position="inner")
        )
            .add(
            series_name=name,
            radius=["25%", "40%"],
            data_pair=data[1],
            label_opts=opts.LabelOpts(
                position="middle",
            )
        )
            .add(
            series_name=name,
            radius=["50%", "80%"],
            data_pair=data[2],
            label_opts=opts.LabelOpts(
                position="middle",
            )
        )
            .set_global_opts(legend_opts=opts.LegendOpts(is_show=False), )
    ).render(os.path.join(CURPATH, "%s.html" % name))


def sun(data, name):
    sunburst = (
        Sunburst(init_opts=opts.InitOpts(width="1340px", height="555px"))
            .add(series_name="", data_pair=data, radius=[0, "100%"])
            .set_global_opts(title_opts=opts.TitleOpts(title=name), )
            .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}"), )
            .render(os.path.join(CURPATH, "旭日图-%s.html" % name))
    )


class dataNode():
    def __init__(self, value) -> None:
        self.son = dict()
        self.value = value
        self.version = None
        self.changeV = False
        self.caseDetail = [0] * htmlnus

    def updateNode(self, args, type=None):
        """
        type: define 1=insertCaseDetail, 2=updateByVersion, 3=updateByOther
        """
        if not type:
            raise Exception("Type is Error")
        if 1 == type:
            return self._insertCaseDetail(args)
        elif 2 == type:
            return self._updateByVersion(args)
        elif 3 == type:
            return self._updateByVersionUp(args)
        else:
            return self._updateByOther(args)

    def _insertCaseDetail(self, args):
        assert (len(args) == htmlnus)
        for _, detail in enumerate(args, 0):
            self.caseDetail[_] = detail
            print(self.caseDetail)
            yield self.caseDetail[_]

    def _updateByVersion(self, args):
        assert (len(args) == htmlnus)
        for _, detail in enumerate(args, 0):
            temp, self.caseDetail[_] = detail - self.caseDetail[_], detail
            yield temp

    def _updateByVersionUp(self, args):
        assert (len(args) == htmlnus)
        self.changeV = True
        for _, detail in enumerate(args, 0):
            self.caseDetail[_] = self.caseDetail[_] + detail
            yield detail

    def _updateByOther(self, args):
        assert (len(args) == htmlnus)
        for _, detail in enumerate(args, 0):
            self.caseDetail[_] = detail + self.caseDetail[_]
            yield detail


indexList = [dict() for i in range(3)]  # indexList={list:3}[{},{},{}]
parentNode = dataNode(None)


def insertNode(itera, row):
    """
    闭包加递归，实现树形结构
    """

    def insert(myNode, level):
        value = itera.cell_value(row, values[level])
        # print(value)
        if myNode.version:
            return myNode.updateNode([int(itera.cell_value(row, i)) for i in values[4:]], 1)

        if not myNode.son.get(value):
            Node = dataNode(value)
            # print(Node)
            myNode.son[value] = Node
            if level == 2:
                Node.version = itera.cell_value(row, values[3])
            return myNode.updateNode(list(insert(Node, level + 1)), 4)

        else:
            if level == 2:
                if myNode.son.get(value).version <= itera.cell_value(row, values[3]):
                    myNode.son.get(value).version = itera.cell_value(row, values[3])
                    return myNode.updateNode(list(myNode.son.get(value).updateNode(
                        [int(itera.cell_value(row, i)) for i in values[4:]], 2)), 3)
            if myNode.son.get(value).changeV:
                myNode.son.get(value).changeV = False
                return myNode.updateNode(list(insert(myNode.son.get(value), level + 1)), 3)
            return myNode.updateNode(list(insert(myNode.son.get(value), level + 1)), 4)

    insert(parentNode, 0)


def parseData():
    sheet_object = loadsheet()
    nrows = sheet_object.nrows
    # print(nrows)
    for row in range(1, nrows):
        insertNode(sheet_object, row)


def PieData(index):
    """
    遍历self.son = dict()
    单链表结构实现
    """
    x_data = [[], [], []]
    y_data = [[], [], []]
    for son_one in parentNode.son.keys():
        x_data[0].append(son_one)
        y_data[0].append(parentNode.son[son_one].caseDetail[index])

        for son_two in parentNode.son[son_one].son.keys():
            x_data[1].append(son_two)
            y_data[1].append(parentNode.son[son_one].son[son_two].caseDetail[index])

            for son_three in parentNode.son[son_one].son[son_two].son.keys():
                x_data[2].append(son_three)
                y_data[2].append(parentNode.son[son_one].son[son_two].son[son_three].caseDetail[index])

    res = []
    for i in range(3):
        res.append([list(z) for z in zip(x_data[i], y_data[i])])
    # print(res)
    return res


def sunburstData(index):
    from pyecharts import options as opts
    retData = list()
    for son_one in parentNode.son.keys():
        innerDatatwo = list()
        for son_two in parentNode.son[son_one].son.keys():
            innerDatathree = list()
            for son_three in parentNode.son[son_one].son[son_two].son.keys():
                itemthree = opts.SunburstItem(name=son_three, \
                                              value=parentNode.son[son_one].son[son_two].son[son_three].caseDetail[
                                                  index])
                innerDatathree.append(itemthree)
            itemtwo = opts.SunburstItem(name=son_two, \
                                        value=parentNode.son[son_one].son[son_two].caseDetail[index],
                                        children=innerDatathree)
            innerDatatwo.append(itemtwo)
        item = opts.SunburstItem(name=son_one, value=parentNode.son[son_one].caseDetail[index], children=innerDatatwo)
        retData.append(item)
    return retData


if __name__ == "__main__":
    for name in values.keys():
        parseData(name)
    # Pies中的字典为excel最终产生文件的命名
# Pies = {
#     0: "自动化测试服务接口个数",
#     1: "自动化测试新增接口个数",
#     2: "自动化测试用例总数",
#     3: "自动化测试用例执行成功个数",
#     4: "自动化测试用例执行失败个数",
#     5: "自动化测试用例执行总数",
#     6: "自动化测试测试总轮次",
#     7: "自动化测试缺陷总数"
# }
# for k, v in Pies.items():
    # myPie(PieData(k), v)

        for x, y in enumerate (values[name]["colname"]):
            sun(sunburstData(x), y)